package com.martin.videoplayer.video;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.askpert.review.R;
import com.askpert.review.activity.home.ShopDetalisActivity2;
import com.askpert.review.activity.my.AbsVideoCommentActivity;
import com.askpert.review.activity.my.MyHomepageActivity;
import com.askpert.review.activity.video.TopicVideoActivity;
import com.askpert.review.bean.UserBean;
import com.askpert.review.dialog.ReportTypeDialog;
import com.askpert.review.dialog.VideoDownIngDialog;
import com.askpert.review.dialog.VideoMoreDialog;
import com.askpert.review.downLoad.DownloadUtil;
import com.askpert.review.event.VideoCommentEvent;
import com.askpert.review.http.HTTP;
import com.askpert.review.http.HttpCallback;
import com.askpert.review.permissions.OnPermissionCallback;
import com.askpert.review.permissions.Permission;
import com.askpert.review.permissions.XXPermissions;
import com.askpert.review.util.DateUtils;
import com.askpert.review.util.LanguageStore;
import com.askpert.review.util.ShareUtils;
import com.askpert.review.util.ToastUtil;
import com.askpert.review.views.AbsViewHolder;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tencent.rtmp.TXVodPlayer;
import com.xuexiang.xui.widget.flowlayout.BaseTagAdapter;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.List;

/**
 * Created by cxf on 2018/11/26.
 * 视频播放外框二期
 */

public class VideoPlayWrapViewHolder extends AbsViewHolder implements View.OnClickListener {

    private ViewGroup mVideoContainer;
    private ImageView mCover;
    private ImageView mAvatar;
    private TextView mName;
    private TextView copywriting;//内容
    private ImageView mBtnLike;//点赞按钮
    private TextView mLikeNum;//点赞数
    private TextView mCommentNum;//评论数
    private TextView mShareNum;//分享数
    private ImageView mBtnFollow;//关注按钮
    private ImageView more;
    private TextView mTvDate;
    private VideoBean mVideoBean;
    private Drawable mFollowDrawable;//已关注
    private Drawable mUnFollowDrawable;//未关注
    private Animation mFollowAnimation;
    private boolean mCurPageShowed;//当前页面是否可见
    private ValueAnimator mLikeAnimtor;
    private Drawable[] mLikeAnimDrawables;//点赞帧动画
    private int mLikeAnimIndex;
    private ViewGroup mCommentParent;
    private Context context;
    private ImageView start1;
    private ImageView start2;
    private ImageView start3;
    private ImageView start4;
    private ImageView start5;
    private TextView shop_points;
    private RoundedImageView shopIcon;
    private TextView shopTitle;
    private TextView shopIntroduce;
    private ImageView isAttestation;
    FlowTagLayout mNormalFlowTagLayout;
    private TextView mTvVideoCurTime, mTvVideoTotalTime;
    private SeekBar mVideoSeekBar;
    private LinearLayout timeLayout;

    public VideoPlayWrapViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
        this.context = context;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.item_active_video;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void init() {
        EventBus.getDefault().register(this);
        mVideoContainer = findViewById(R.id.video_container);
        //商铺
        shopIcon = findViewById(R.id.shop_image);
        shopTitle = findViewById(R.id.shop_title);
        shopIntroduce = findViewById(R.id.shop_introduce);
        isAttestation = findViewById(R.id.is_attestation);
        mTvVideoCurTime = findViewById(R.id.tv_video_current_time);
        mTvVideoTotalTime = findViewById(R.id.tv_video_total_time);
        mVideoSeekBar = findViewById(R.id.video_seek_bar);
        timeLayout = findViewById(R.id.timeLayout);
        mCommentParent = findViewById(R.id.fl_comment);
        mCover = findViewById(R.id.video_cover);
        mAvatar = findViewById(R.id.avatar);
        mName = findViewById(R.id.name);
        copywriting = findViewById(R.id.copywriting);
        mBtnLike = findViewById(R.id.btn_like);
        mLikeNum = findViewById(R.id.like_num);
        mCommentNum = findViewById(R.id.comment_num);
        mShareNum = findViewById(R.id.share_num);
        more = findViewById(R.id.more);
        mBtnFollow = findViewById(R.id.btn_follow);
        shop_points = findViewById(R.id.shop_points);
        mNormalFlowTagLayout = findViewById(R.id.flowlayout_normal_select);
        start1 = findViewById(R.id.start1);
        start2 = findViewById(R.id.start2);
        start3 = findViewById(R.id.start3);
        start4 = findViewById(R.id.start4);
        start5 = findViewById(R.id.start5);

        //mFollowDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_video_follow_1);
        //mUnFollowDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_video_follow_0);
        mAvatar.setOnClickListener(this);
        mBtnFollow.setOnClickListener(this);
        mBtnLike.setOnClickListener(this);
        findViewById(R.id.btn_comment).setOnClickListener(this);
        findViewById(R.id.ll_talk_layout).setOnClickListener(this);
        findViewById(R.id.btn_share).setOnClickListener(this);
        findViewById(R.id.more).setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (context instanceof Activity) {
                    Activity activity = (Activity) context;
                    activity.finish();
                }
            }
        });
        mTvDate = findViewById(R.id.tv_date);
        mVideoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTvVideoCurTime.setText(DateUtils.geSecondToString(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mContext instanceof VideoPlayActivity) {
                    ((VideoPlayActivity) mContext).mVideoPlayViewHolder.pausePlay();//拖动时暂停播放
                    timeLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mContext instanceof VideoPlayActivity) {
                    ((VideoPlayActivity) mContext).mVideoPlayViewHolder.setSeekProgressPlay(seekBar.getProgress());//设置拖动位置
                    ((VideoPlayActivity) mContext).mVideoPlayViewHolder.resumePlay();//松开时继续播放
                    timeLayout.setVisibility(View.GONE);
                }
            }
        });

        mVideoSeekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    default:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        ((VideoPlayActivity) mContext).setNeedIntercept(true);
                }
                return false;
            }
        });

        initLikeAnimtor();
    }
    @SuppressLint("SetTextI18n")
    private void initStar() {
        shop_points.setText(mVideoBean.getScore() + ".0");
        if (mVideoBean.getScore() == 1) {
            Glide.with(context).load(R.mipmap.shop_gradle).into(start1);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start2);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start3);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start4);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start5);
        } else if (mVideoBean.getScore() == 2) {
            Glide.with(context).load(R.mipmap.shop_gradle).into(start1);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start2);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start3);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start4);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start5);
        } else if (mVideoBean.getScore() == 3) {
            Glide.with(context).load(R.mipmap.shop_gradle).into(start1);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start2);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start3);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start4);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start5);
        } else if (mVideoBean.getScore() == 4) {
            Glide.with(context).load(R.mipmap.shop_gradle).into(start1);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start2);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start3);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start4);
            Glide.with(context).load(R.mipmap.shop_gradle2).into(start5);
        } else if (mVideoBean.getScore() == 5) {
            Glide.with(context).load(R.mipmap.shop_gradle).into(start1);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start2);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start3);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start4);
            Glide.with(context).load(R.mipmap.shop_gradle).into(start5);
        }
    }

    VideoMoreDialog dialog;

    /**
     * 短视频-更多
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void chickMore() {
        dialog = new VideoMoreDialog(mContext, mVideoBean);
        dialog.setOnDialogClickListener(new VideoMoreDialog.OnDialogClickListener() {
            @Override
            public void onDownLoadListener() {
                checkP();
                //保存到本地
            }

            @Override
            public void onReportClickListener() {
                //举报
                Report();
            }

            @Override
            public void onCollectClickListener() {
                //收藏
                collect();
            }
        });
        dialog.showPopupWindow();
    }

    /**
     * 收藏
     */
    private void collect() {
        HTTP.videoCollect(mVideoBean.getId(), new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0) {
                    if (mVideoBean.getIsCollect() == 0) {
                        //收藏成功
                        mVideoBean.setIsCollect(1);
                        Toast toast = Toast.makeText(context, context.getResources().getString(R.string.have_collected), Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    } else {
                        //取消收藏
                        mVideoBean.setIsCollect(0);
                        showToast(context.getResources().getString(R.string.cancel_collected));
                        Toast toast = Toast.makeText(context, context.getResources().getString(R.string.cancel_collected), Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    }
                    dialog.dismiss();
                }
            }
        });
    }

    private void checkP() {//.permission("android.permission.UPDATE_DEVICE_STATS")
        XXPermissions.with(context).permission(Permission.READ_EXTERNAL_STORAGE).permission(Permission.WRITE_EXTERNAL_STORAGE).request(new OnPermissionCallback() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                if (all) {
                    downLoadVideo(mVideoBean.getVideoUrl());
                } else {
                    ToastUtil.show("获取部分权限成功，但部分权限未正常授予");
                }
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                if (never) {
                    ToastUtil.show("被永久拒绝授权，请手动授予权限");
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    XXPermissions.startPermissionActivity(context, permissions);
                } else {
                    ToastUtil.show("获取权限失败");
                }
            }
        });
    }

    VideoDownIngDialog videoDownIngDialog;

    File downLoadFile;

    /**
     * 保存视频
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void downLoadVideo(String path) {

        String path1 = context.getExternalCacheDir().getPath();

        videoDownIngDialog = new VideoDownIngDialog(context);
        videoDownIngDialog.showPopupWindow();
        DownloadUtil.get().download(path, path1, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                downLoadFile = file;
                handler.sendEmptyMessage(-1);
            }

            @Override
            public void onDownloading(int progress) {
                handler.sendEmptyMessage(progress);
            }

            @Override
            public void onDownloadFailed() {
                handler.sendEmptyMessage(-2);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1) {
                Log.d("TAG", "handleMessage: " + new Gson().toJson(downLoadFile));
                DownloadUtil.createFiles(downLoadFile);
                videoDownIngDialog.setProgressSuccess();
                videoDownIngDialog.dismiss();
                dialog.dismiss();
            } else if (msg.what == -2) {
                videoDownIngDialog.dismiss();
                Toast.makeText(context, context.getString(R.string.video_download_failed), Toast.LENGTH_SHORT).show();
            } else {
                videoDownIngDialog.setProgress(msg.what);
            }
        }
    };

    /**
     * 举报
     */
    private void Report() {
        ReportTypeDialog reportTypeDialog = new ReportTypeDialog(mContext, mVideoBean.getId(), 3);
        reportTypeDialog.setOnDialogClickListener(() -> {

        });
        reportTypeDialog.showPopupWindow();
    }

    /**
     * 初始化点赞动画
     */
    private void initLikeAnimtor() {
        if (mLikeAnimDrawables != null && mLikeAnimDrawables.length > 0) {
            mLikeAnimtor = ValueAnimator.ofFloat(0, mLikeAnimDrawables.length);
            mLikeAnimtor.setDuration(800);
            mLikeAnimtor.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float v = (float) animation.getAnimatedValue();
                    int index = (int) v;
                    if (mLikeAnimIndex != index) {
                        mLikeAnimIndex = index;
                        if (mBtnLike != null && mLikeAnimDrawables != null && index < mLikeAnimDrawables.length) {
                            mBtnLike.setImageDrawable(mLikeAnimDrawables[index]);
                        }
                    }
                }
            });
        }
    }

    /**
     * 初始化关注动画
     */
    public void initFollowAnimation() {
        mFollowAnimation = new ScaleAnimation(1, 0.3f, 1, 0.3f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mFollowAnimation.setRepeatMode(Animation.REVERSE);
        mFollowAnimation.setRepeatCount(1);
        mFollowAnimation.setDuration(200);
        mFollowAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                if (mBtnFollow != null && mVideoBean != null) {
                    /*if (mVideoBean.getAttent() == 1) {
                        mBtnFollow.setImageDrawable(mFollowDrawable);
                    } else {
                        mBtnFollow.setImageDrawable(mUnFollowDrawable);
                    }*/
                }
            }
        });
    }

    public void setLikeAnimDrawables(Drawable[] drawables) {
        mLikeAnimDrawables = drawables;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setData(VideoBean bean, Object payload) {
        if (bean == null) {
            return;
        }
        mVideoBean = bean;
        initStar();
        if (mVideoBean.getShops() != null) {
            shopIcon = findViewById(R.id.shop_image);
            shopTitle.setText(mVideoBean.getShops().getName());
            shopIntroduce.setText(mVideoBean.getShops().getDes());
            if (mVideoBean.getShops().getStatus() == 1) {
                isAttestation.setImageDrawable(context.getResources().getDrawable(R.mipmap.iconf_auth_1));
            }
            if (mVideoBean.getShops().getThumb() != null) {
                Glide.with(context).load(mVideoBean.getShops().getThumb()).into(shopIcon);
            }
            findViewById(R.id.shop_detalis).setVisibility(View.VISIBLE);
            findViewById(R.id.shop_detalis).setOnClickListener(v -> ShopDetalisActivity2.forward(context, mVideoBean.getShops().getId() + ""));
        } else {
            findViewById(R.id.shop_detalis).setVisibility(View.GONE);
        }
        UserBean u = mVideoBean.getUsers();
        if (payload == null) {
            if (mCover != null) {
                setCoverImage();
            }
            if (copywriting != null) {
                //拼接话题
                /*SpannableStringBuilder builder = new SpannableStringBuilder();
                // builder.append(bean.getDesc()).append("  ");
                int lengthTile = builder.toString().length();
                if (bean.getNewTopPics() != null) {
                    List<VideoBean.NewTopPic> topic = bean.getNewTopPics();
                    for (VideoBean.NewTopPic map : topic) {
                        builder.append("#").append(map.getTopicName());
                    }
                }
                int length = builder.toString().length();
                builder.setSpan(new StyleSpan(Typeface.BOLD), lengthTile, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                topic.setText(builder);*/

                copywriting.setText(bean.getDesc());
               /* TagAdapter tagAdapter = new TagAdapter(R.layout.item_video_tag, mVideoBean.getNewTopPics());
                tagAdapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                        TopicVideoActivity.forward(context, mVideoBean.getNewTopPics().get(position).getTopicId(), mVideoBean.getNewTopPics().get(position).getTopicName());
                    }
                });
                */

                List<VideoBean.NewTopPic> tempList = mVideoBean.getNewTopPics();

                FlowTagAdapter tagAdapter = new FlowTagAdapter(context);
                mNormalFlowTagLayout.setAdapter(tagAdapter);
                mNormalFlowTagLayout.setOnTagClickListener((parent, view, position) -> {
                    TopicVideoActivity.forward(context, mVideoBean.getNewTopPics().get(position).getTopicId(), mVideoBean.getNewTopPics().get(position).getTopicName());
                });
                tagAdapter.addTags(tempList);
            }
            if (u != null) {
                if (mAvatar != null) {
                    ImgLoader.displayAvatar(mContext, u.getAvatar(), mAvatar);
                }
                if (mName != null) {
                    mName.setText("@" + u.getUser_nickname());
                }
            }
        }
        if (mBtnLike != null) {
            if (bean.getLike() == 1) {
                if (mLikeAnimDrawables != null && mLikeAnimDrawables.length > 0) {
                    mBtnLike.setImageDrawable(mLikeAnimDrawables[mLikeAnimDrawables.length - 1]);
                }
            } else {
                mBtnLike.setImageResource(R.mipmap.icon_video_zan_01);
            }
        }
        if (mLikeNum != null) {
            mLikeNum.setText(bean.getLikes());
        }
        if (mCommentNum != null) {
            mCommentNum.setText(bean.getComments());
        }
        if (mShareNum != null) {
            mShareNum.setText(bean.getShares());
        }
       /* if (u != null && mBtnFollow != null) {
            String toUid = u.getId();
            if (!TextUtils.isEmpty(toUid) && !toUid.equals(CommonAppConfig.getInstance().getUid())) {
                if (mBtnFollow.getVisibility() != View.VISIBLE) {
                    mBtnFollow.setVisibility(View.VISIBLE);
                }
                if (bean.getAttent() == 1) {
                    mBtnFollow.setImageDrawable(mFollowDrawable);
                } else {
                    mBtnFollow.setImageDrawable(mUnFollowDrawable);
                }
            } else {
                if (mBtnFollow.getVisibility() == View.VISIBLE) {
                    mBtnFollow.setVisibility(View.INVISIBLE);
                }
            }
        }*/
        if (mTvDate != null) {
            mTvDate.setText(" · " + DateUtils.formatHowTimeAgo(bean.getCreatetime()));
        }
    }

    public class FlowTagAdapter extends BaseTagAdapter<VideoBean.NewTopPic, TextView> {

        public FlowTagAdapter(Context context) {
            super(context);
        }

        @Override
        protected TextView newViewHolder(View convertView) {
            return convertView.findViewById(R.id.name);
        }

        @Override
        protected int getLayoutId() {
            return R.layout.item_tags;
        }

        @Override
        protected void convert(TextView textView, VideoBean.NewTopPic item, int position) {
            textView.setText("#" + item.getTopicName());
        }
    }

    private class TagAdapter extends BaseQuickAdapter<VideoBean.NewTopPic, BaseViewHolder> {

        public TagAdapter(int layoutResId, List<VideoBean.NewTopPic> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, VideoBean.NewTopPic topicBean) {
            baseViewHolder.setText(R.id.text, "#" + topicBean.getTopicName());
        }
    }

    private void setCoverImage() {
        ImgLoader.displayDrawable(mContext, mVideoBean.getVideoImage(), new ImgLoader.DrawableCallback() {
            @Override
            public void onLoadSuccess(Drawable drawable) {
                if (mCover != null && drawable != null) {
                    float w = drawable.getIntrinsicWidth();
                    float h = drawable.getIntrinsicHeight();
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mCover.getLayoutParams();
                    int targetH = 0;
                    if (w / h > 0.5625f) {//横屏  9:16=0.5625
                        targetH = (int) (mCover.getWidth() / w * h);
                    } else {
                        targetH = ViewGroup.LayoutParams.MATCH_PARENT;
                    }
                    if (targetH != params.height) {
                        params.height = targetH;
                        mCover.requestLayout();
                    }
                    mCover.setImageDrawable(drawable);
                }
            }

            @Override
            public void onLoadFailed() {

            }
        });
    }

    public void addVideoView(View view) {
        if (mVideoContainer != null && view != null) {
            ViewParent parent = view.getParent();
            if (parent != null) {
                ViewGroup viewGroup = (ViewGroup) parent;
                if (viewGroup != mVideoContainer) {
                    viewGroup.removeView(view);
                    mVideoContainer.addView(view);
                }
            } else {
                mVideoContainer.addView(view);
            }
        }
    }

    public VideoBean getVideoBean() {
        return mVideoBean;
    }

    /**
     * 获取到视频首帧回调
     */
    public void onFirstFrame(TXVodPlayer txVodPlayer) {
        if (mCover != null && mCover.getVisibility() == View.VISIBLE) {
            mCover.setVisibility(View.INVISIBLE);
        }
        if (txVodPlayer != null) {
            int duration = (int) txVodPlayer.getDuration();
            if (duration < 20) {//20秒以内不显示控件不设值
                mVideoSeekBar.setVisibility(View.GONE);
                mTvVideoTotalTime.setVisibility(View.GONE);
                mTvVideoCurTime.setVisibility(View.GONE);
                return;
            } else {
                mVideoSeekBar.setVisibility(View.VISIBLE);
                mTvVideoTotalTime.setVisibility(View.VISIBLE);
                mTvVideoCurTime.setVisibility(View.VISIBLE);
            }
            mVideoSeekBar.setMax(duration);
            String totalTime = "  /  " + DateUtils.geSecondToString(duration);
            mTvVideoTotalTime.setText(totalTime);
        }
    }


    /**
     * 当前视频播放进度时间
     */
    public void onCurrentPlayTime(int currentTime) {
        mVideoSeekBar.setProgress(currentTime);
        mTvVideoCurTime.setText(DateUtils.geSecondToString(currentTime));
    }

    /**
     * 滑出屏幕
     */
    public void onPageOutWindow() {
        mCurPageShowed = false;
        if (mCover != null && mCover.getVisibility() != View.VISIBLE) {
            mCover.setVisibility(View.VISIBLE);
            ((AbsVideoCommentActivity) mContext).hideCommentWindow(false);
        }
    }

    /**
     * 滑入屏幕
     */
    public void onPageInWindow() {
        if (mCover != null) {
            if (mCover.getVisibility() != View.VISIBLE) {
                mCover.setVisibility(View.VISIBLE);
            }
            mCover.setImageDrawable(null);
            setCoverImage();
        }
    }

    /**
     * 滑动到这一页 准备开始播放
     */
    public void onPageSelected() {
        mCurPageShowed = true;
    }

    @Override
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void onClick(View v) {
        if (!canClick()) {
            return;
        }
        int i = v.getId();
        if (i == R.id.btn_follow) {
            clickFollow();
        } else if (i == R.id.btn_comment || i == R.id.ll_talk_layout) {
            clickComment();
        } else if (i == R.id.btn_share) {
            clickShare();
        } else if (i == R.id.btn_like) {
            clickLike();
        } else if (i == R.id.avatar) {
            clickAvatar();
        } else if (i == R.id.more) {
            chickMore();
        }
    }

    /**
     * 点击  查看同款商品
     */
    private void clickGoods() {
        if (mContext != null && mVideoBean != null) {
            /*if (mVideoBean.getType() == 1) {//商品
                if (mVideoBean.getGoodsType() == 0) {
                    RouteUtil.forwardGoodsDetail(mVideoBean.getGoodsId(), false);
                } else {
                    RouteUtil.forwardGoodsDetailOutSide(mVideoBean.getGoodsId(), false);
                }
            } else if (mVideoBean.getType() == 2) {//付费内容
                RouteUtil.forwardPayContentDetail(mVideoBean.getGoodsId());
            }*/
        }
    }

    /**
     * 点击头像
     */
    public void clickAvatar() {
        if (mVideoBean != null) {
            if (mContext instanceof VideoPlayActivity) {
                ((VideoPlayActivity) mContext).mVideoPlayViewHolder.pagerChangePausePlay();
            }
            MyHomepageActivity.forward(mContext, mVideoBean.getUid() + "");
        }
    }

    /**
     * 点赞,取消点赞
     */
    private void clickLike() {
        if (mVideoBean == null) {
            return;
        }
        HTTP.setVideoLike(mVideoBean.getId(), new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    String likeNum = obj.getString("count");
                    int like = obj.getIntValue("like");
                    if (mVideoBean != null) {
                        mVideoBean.setLikes(likeNum);
                        //mVideoBean.set(like);
                        if (mLikeNum != null) {
                            mLikeNum.setText(likeNum);
                        }
                    }
                    if (mLikeNum != null) {
                        mLikeNum.setText(likeNum);
                    }
                    if (mBtnLike != null) {
                        if (like == 1) {
                            if (mLikeAnimtor == null) {
                                initLikeAnimtor();
                            }
                            mLikeAnimIndex = -1;
                            if (mLikeAnimtor != null) {
                                mLikeAnimtor.start();
                            }
                        } else {
                            mBtnLike.setImageResource(R.mipmap.icon_video_zan_01);
                        }
                    }

                } else {
                    ToastUtil.show(LanguageStore.translation(msg));
                }
            }
        });
    }

    /**
     * 点击关注按钮
     */
    private void clickFollow() {
        if (mVideoBean == null) {
            return;
        }
        /*final UserBean u = mVideoBean.getUserBean();
        if (u == null) {
            return;
        }
        CommonHttpUtil.setAttention(mTag, u.getId(), new CommonCallback<Integer>() {
            @Override
            public void callback(Integer attent) {
                mVideoBean.setAttent(attent);
                if (mCurPageShowed) {
                    if (mFollowAnimation == null) {
                        initFollowAnimation();
                    }
                    mBtnFollow.startAnimation(mFollowAnimation);
                } else {
                    if (attent == 1) {
                        mBtnFollow.setImageDrawable(mFollowDrawable);
                    } else {
                        mBtnFollow.setImageDrawable(mUnFollowDrawable);
                    }
                }
            }
        });*/
    }

    /**
     * 点击评论按钮
     */
    private void clickComment() {
        ((AbsVideoCommentActivity) mContext).openCommentWindow(mVideoBean.getId(), mVideoBean.getUid() + "", mVideoBean.getComments(), mCommentParent);
    }

    /**
     * 点击分享按钮
     */
    private void clickShare() {
        if (mVideoBean == null) {
            return;
        }
        ShareUtils.sendText(context, mVideoBean.getShareUrl(), "分享");

        //通知后台
        /*HTTP.shareVideo(mVideoBean.getId(), new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                Log.d("TAG", "onSuccess: " + new Gson().toJson(info));
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    String likeNum = obj.getString("count");
                    if (likeNum != null) {
                        mShareNum.setText(likeNum);
                    }
                } else {
                    ToastUtil.show(LanguageStore.translation(msg));
                }
            }
        });*/
    }

    public void release() {
        //VideoHttpUtil.cancel(mTag);
        if (mLikeAnimtor != null) {
            mLikeAnimtor.cancel();
        }
        if (mBtnFollow != null && mFollowAnimation != null) {
            mBtnFollow.clearAnimation();
        }
    }

    @Subscribe
    public void commentResultEvent(VideoCommentEvent event) {
        if (mCommentNum != null && event != null && mVideoBean != null) {
            mVideoBean.setComments(event.getCommentNum());
            mCommentNum.setText(event.getCommentNum());
        }
    }

    //继续播放
    public void resumePlay() {
        ((VideoPlayActivity) mContext).mVideoPlayViewHolder.resumePlay();
    }

    //页面不可见，视频停止播放
    public void pausePlay() {
        ((VideoPlayActivity) mContext).mVideoPlayViewHolder.pausePlay();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().register(this);
        super.onDestroy();
    }
}
